# -*- coding:utf-8 -*-
import getopt
import locale
import os
import platform
import pysvn
import shutil
import socket
import struct
import sys
import fcntl
from pylib import SuperxGit

from pylib.utils import *
from pylib.svn_utils import *
from pylib.git_utils import *

HOME_PATH = os.path.expanduser('~')
WORKSPACE_PATH = os.path.dirname(os.path.abspath(__file__))

PROJECT_PY = 'build.py'
PROJECT_CONFIG_FILE = '.project'
VERSION_PROPERTIES = '%s/%s/version.properties/%s'

BUILD_OUT_PATH = '%s/%s/%s/build/outputs/'
BUILD_OUT_APKS_PATH = '%s/apk/' % BUILD_OUT_PATH
BUILD_OUT_MAPPING_PATH = '%s/mapping/' % BUILD_OUT_PATH

RELEASE_PATH = '%s/Release/' % WORKSPACE_PATH

TEST_REPORT_PATH = '%s/TestReport/' % WORKSPACE_PATH

MAIL_TO = 'luyuxiang@skyworth.com,liqiwen@skyworth.com,luwei@skyworth.com,tengliang@skyworth.com,xufukang@skyworth.com,tangsijing@skyworth.com,hushuang@skyworth.com,lijiaming@skyworth.com,xuzexiao@skyworth.com'

my_platform = platform.system().lower()


#################################################################################################

class ProjectConfig:
    KEY_PROJECT_NAME = 'NAME'
    KEY_GIT_REPO_URL = 'GIT_REPO_URL'
    project_name = ''
    git_repo_url = ''


def load_project_config():
    pcs = []
    files = os.listdir(WORKSPACE_PATH)
    for _file in files:
        _file = '%s/%s' % (WORKSPACE_PATH, _file)
        if _file.endswith(PROJECT_CONFIG_FILE) == True:
            pc = ProjectConfig()
            pcs.append(pc)
            file_object = open(_file, 'r')
            lines = file_object.readlines()
            file_object.close()
            for line in lines:
                kv = line.split('=')
                if ProjectConfig.KEY_PROJECT_NAME in kv[0]:
                    pc.project_name = kv[1].strip('\n')
                elif ProjectConfig.KEY_GIT_REPO_URL in kv[0]:
                    pc.git_repo_url = kv[1].strip('\n')
    return pcs


def init_project(pc):
    path = '%s/%s' % (WORKSPACE_PATH, pc.project_name)
    if os.path.exists(path) == True:
        os.rmdir(path)
    SuperxGit.clone(pc.git_repo_url, path)


def build_project(pc, branch, apps):
    log('start build_project %s:%s:%s' % (pc.project_name, branch, apps))
    ret = dict()
    os.chdir('%s/%s' % (WORKSPACE_PATH, pc.project_name))
    SuperxGit.branch(branch)
    revision = SuperxGit.pull(pc.git_repo_url, branch)[0:7]
    os.system('python %s --build %s' % (PROJECT_PY, branch))
    os.system("gradle clean")
    for app in apps:
        out_apks_path = get_build_out_apks_path(pc.project_name, app)
        log('ready to build %s  out_apks_path:%s' % (app, out_apks_path))
        try:
            if os.path.exists(out_apks_path) == True:
                os.rmdir(out_apks_path)
        except Exception as err:
            log(str(err))

        # setup_build_project(build_path, project);
        if os.system("gradle assembleRelease -p %s" % app) == 0:
            major, minor, build = get_build_version(pc.project_name, app)
            release_path = release_apk(out_apks_path, pc.project_name, app, major, minor, build, revision)

            subject = '%s/%s ver:%s 编译完成' % (pc.project_name, app, '%s.%s.%s.%s' % (major, minor, build, revision))
            content = '下载地址:ftp://%s/%s\n' % (get_ip_address('em1'), release_path[len(HOME_PATH):len(release_path)])
            content += '账号:superx 密码:\''
            to = MAIL_TO
            mail(subject, content, to)
            ret[app] = release_path

    os.chdir(WORKSPACE_PATH)
    log('build_project %s:%s:%s end' % (pc.project_name, branch, apps))
    return ret


def test_app(device_ip, pc, apps):
    os.chdir('%s/%s' % (WORKSPACE_PATH, pc.project_name))
    for (app, apks_path) in apps.items():
        apks = os.listdir(apks_path)
        for apk in apks:
            apk_file = "%s/%s" % (apks_path, apk)
            if apk_file.endswith('.apk') == False:
                continue
            result_out = '%s/%s/%s/%s' % (TEST_REPORT_PATH, pc.project_name, app, apk)
            os.system('python %s --test %s,%s,%s,%s' % (PROJECT_PY, device_ip, app, apk_file, result_out))

            subject = '%s/%s/%s ver:%s 测试完成' % (pc.project_name, app, apk)
            content = '测试报告地址:http://%s/TestReport/%s\n' % (
                get_ip_address('em1'), result_out[len(TEST_REPORT_PATH):len(result_out)])
            to = MAIL_TO
            mail(subject, content, to)
    os.chdir(WORKSPACE_PATH)


def release_apk(out_apks_path, project, app, major, minor, build, rev):
    apks = os.listdir(out_apks_path)
    for apk in apks:
        apk_file = "%s/%s" % (out_apks_path, apk)
        if apk_file.endswith(".apk") == False:
            os.remove(apk_file)
        elif apk_file.find("unaligned") >= 0:
            os.remove(apk_file)
        elif apk_file.find("release") <= 0:
            os.remove(apk_file)

    release_path = '%s/%s/%s/%s/%s' % (
        RELEASE_PATH, project, app, '%s.%s' % (major, minor), '%s.%s.%s.%s' % (major, minor, build, rev))
    log('release apk from %s to %s' % (out_apks_path, release_path))
    shutil.copytree(out_apks_path, release_path)
    try:
        mapping_src = get_build_out_mapping_path(project, app)
        mapping_dst = '%s/mapping' % release_path
        log('release mapping from %s to %s' % (mapping_src, mapping_dst))
        shutil.copytree(mapping_src, mapping_dst)
    except Exception as err:
        log(str(err))
    return release_path


def get_build_out_path(project, app):
    return BUILD_OUT_PATH % (WORKSPACE_PATH, project, app)


def get_build_out_apks_path(project, app):
    return BUILD_OUT_APKS_PATH % (WORKSPACE_PATH, project, app)


def get_build_out_mapping_path(project, app):
    return BUILD_OUT_MAPPING_PATH % (WORKSPACE_PATH, project, app)


def get_version_properties_file(project, app):
    return VERSION_PROPERTIES % (WORKSPACE_PATH, project, app)


def get_build_version(project, app):
    version_major = 0
    version_minor = 0
    version_build = 0
    file_object = open(get_version_properties_file(project, app), 'r')
    lines = file_object.readlines()
    log(lines)
    file_object.close()
    for line in lines:
        kv = line.split('=')
        if 'VERSION_MAJOR' in kv[0]:
            version_major = int(kv[1])
        elif 'VERSION_MINOR' in kv[0]:
            version_minor = int(kv[1])
        elif 'VERSION_BUILD' in kv[0]:
            version_build = int(kv[1])
    return version_major, version_minor, version_build


def _usage():
    pass


def _main(argv):
    opts, args = getopt.getopt(argv[1:], 's', ['init', 'help', 'build=', 'test='])
    if len(opts) == 0:
        _usage()
        sys.exit(1)

    try:
        for o, a in opts:
            if o in ('--help'):
                _usage()
                sys.exit(1)
            elif o in ('--init'):
                if len(a) == 0:
                    pcs = load_project_config()
                    for pc in pcs:
                        init_project(pc)
                else:
                    bp = a.split(':')
                    pc = ProjectConfig()
                    pc.project_name = bp[0]
                    pc.git_repo_url = bp[1]
                    init_project(pc)
                sys.exit(0)
            elif o in ('--build'):
                bp = a.split(':')
                project = bp[0]
                branch = bp[1]
                apps = bp[2].split(',')
                log('build project:%s' % project)
                log('build branch:%s' % branch)
                log('build apps:%s' % apps)
                pcs = load_project_config()
                device_ip = None
                for oo, aa in opts:
                    if oo in ('--test'):
                        device_ip = aa
                        break
                for pc in pcs:
                    log('%s %s' % (pc.project_name, project))
                    if cmp(pc.project_name, project) == 0:
                        out = build_project(pc, branch, apps)
                        if device_ip != None:
                            test_app(device_ip, pc, out)
                        break
                sys.exit(1)
            else:
                log('unhandled option')
                sys.exit(3)
    except Exception as err:
        log(err)
        _usage()
        sys.exit(1)


if __name__ == '__main__':
    reload(sys)
    sys.path.append(WORKSPACE_PATH)
    sys.setdefaultencoding('utf8')
    if 'linux' in my_platform:
        setlocale()
        # shutil.copytree('/home/lu/workspace/skyworth/SuperX/Workspace/B2.6/AppStore/assets', '/home/lu/aaaaa', False, )
        # main(sys.argv)
    _main(sys.argv)

    # s = os.path.expanduser('~')
    # ss = '/home/lu/workspace/superx_build/Release//superx/AppStore/2.9.801.0b66cba'
    # print(ss[len(s):len(ss)])
    # pcs = load_project_config()
    # for pc in pcs:
    #     log('%s|%s' % (pc.project_name, pc.git_repo_url))
